﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using SharpSvn;
using SVNObject = GraphicalSVN.GraphicSource.Dto.SVNObject;
using SVNRevision = GraphicalSVN.GraphicSource.Dto.SVNRevision;

namespace GraphicalSVN.GraphicSource
{
    public class TreeViewGenerator
    {

        public void StoreTreeInfo(SvnLogEventArgs logEvent, List<SVNObject> svnObjects)
        {
            if (logEvent == null)
            {
                throw new ArgumentNullException("LogEvent in StoreTreeInfo is Null");
            }

            long revisionNumber = logEvent.Revision;
            DateTime dateOfRevision = logEvent.Time;
            foreach(var item in logEvent.ChangedPaths)
            {
                SvnChangeAction action = item.Action;
                string path = item.Path;
                

                SVNRevision revision = new SVNRevision() 
                { 
                    Action = action, 
                    RevisionDate = dateOfRevision, 
                    RevisionNumber = revisionNumber 
                };
                
                SVNObject objectEntry = ReturnObject(svnObjects, path);
                objectEntry.AddRevision(revision);
            }            
        }

        private SVNObject ReturnObject(List<SVNObject> svnObjects, string objectPath)
        {
            if (!svnObjects.Any(x => x.ObjectPath == objectPath))
            {
                Regex re = new Regex(".+(?=/)");
                string path = re.Match(objectPath).Value;
                if (string.IsNullOrEmpty(path))
                {
                    path = "/";
                }
                svnObjects.Add(new SVNObject() { ObjectPath = objectPath, ParentDirectory = path, IsDirectory = false });
            }

            return svnObjects.Where(x => x.ObjectPath == objectPath).First();
        }
    }
}
